// 'use strick'
// 用户数据
const account1 = {
    owner: "Jonas Schmedtmann",
    movements: [200, 455, -306, 25000, -642, -133, 79, 1300],
    interestRate: 1.2, // %
    pin: 1111,
};

const account2 = {
    owner: "Jessica Davis",
    movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30],
    interestRate: 1.5,
    pin: 2222,
};

const accounts = [account1, account2];

// 获取元素
const labelWelcome = document.querySelector('.welcome');
const labelDate = document.querySelector(".balance_data");
const labelBalance = document.querySelector(".balance_value");
const labelSumIn = document.querySelector(".summary_value--in");
const labelSumOut = document.querySelector(".summary_value--out");
const labelSumInterest = document.querySelector(".summary_value--interest");
const labelTimer = document.querySelector(".timer");

const containerApp = document.querySelector(".app");
const containerMovements = document.querySelector(".movements");

const btnLogin = document.querySelector(".login_btn");
const btnTransfer = document.querySelector(".form__btn--transfer");
const btnLoan = document.querySelector(".form__btn--loan");
const btnClose = document.querySelector(".form__btn--close");
const btnSort = document.querySelector(".btn--sort");

const inputLoginUsername = document.querySelector(".login_input--user");
const inputLoginPin = document.querySelector(".login_input--pin");
const inputTransferTo = document.querySelector(".form__input--to");
const inputTransferAmount = document.querySelector(".form__input--amount");
const inputLoanAmount = document.querySelector(".form__input--loan-amount");
const inputCloseUsername = document.querySelector(".form__input--user");
const inputClosePin = document.querySelector(".form__input--pin");

// function

// 更新流水表
const displayMovements = function (movements, sort = false) {
    containerMovements.innerHTML = '';

    const movs = sort ? movements.slice().sort((a, b) => a - b) : movements;

    movs.forEach(function (mov, i) {
        const type = mov > 0 ? 'deposit' : 'withdrawal'

        const html = `
        <div class="movements_row">
            <div class="movements_type movements_type--${type}">${i + 1} ${type}</div>
            <div class="movements_data">3 day ago</div>
            <div class="movements_value">${mov}€</div>
        </div>
        `;

        containerMovements.insertAdjacentHTML('afterbegin', html);
    });
};

// 更新总余额
const displayBalance = function (acc) {
    acc.balance = acc.movements.reduce((acc, mov) => acc + mov);
    labelBalance.textContent = `${acc.balance} €`;
};

// 更新流水总结
const displaySummary = function (acc) {
    const incomes = acc.movements
        .filter(mov => mov > 0)
        .reduce((acc, mov) => acc + mov, 0);
    labelSumIn.textContent = `${incomes}€`;

    const out = acc.movements
        .filter(mov => mov < 0)
        .reduce((acc, mov) => acc + mov, 0);
    labelSumOut.textContent = `${Math.abs(out)}€`;

    const interest = acc.movements
        .filter(mov => mov > 0)
        .map(deposit => ((deposit * acc.interestRate) / 100))
        .filter(int => int >= 1)
        .reduce((acc, int) => acc + int * Math.pow(10, 8), 0) / Math.pow(10, 8);
    labelSumInterest.textContent = `${interest}€`
};


const createUsernames = function (acc) {
    acc.forEach(function (acc) {
        acc.username = acc.owner
            .toLowerCase()
            .split(' ')
            .map(name => name[0])
            .join('');
    });
};

createUsernames(accounts);

// updateUI
const updateUI = function (acc) {
    displayBalance(acc);
    displayMovements(acc.movements);
    displaySummary(acc);
};

// 登陆检查
let currentAcount;

btnLogin.addEventListener('click', function (e) {
    e.preventDefault();

    currentAcount = accounts.find(acc => acc.username === inputLoginUsername.value);

    if (currentAcount?.pin === +inputLoginPin.value) {
        labelWelcome.textContent = `Welcome back, ${currentAcount.owner.split(' ')[0]}`;

        containerApp.style.opacity = 100;

        inputLoginUsername.value = inputLoginPin.value = '';

        inputLoginPin.blur();

        updateUI(currentAcount);
    }
});

btnTransfer.addEventListener('click', function (e) {
    e.preventDefault();

    const amount = +inputTransferAmount.value;
    const receiverAcc = accounts.find(acc => acc.username === inputTransferTo.value);

    inputTransferAmount.value = inputTransferTo.value = '';

    if (amount > 0 && receiverAcc && currentAcount.balance > amount && receiverAcc?.username !== currentAcount.username) {
        currentAcount.movements.push(-amount);
        receiverAcc.movements.push(amount);

        updateUI(currentAcount);
    }
});

btnLoan.addEventListener('click', function (e) {
    e.preventDefault();

    const amount = +inputLoanAmount.value;

    if (amount > 0 && currentAcount.movements.some(mov => mov > amount * 0.1)) {
        currentAcount.movements.push(amount);
        updateUI(currentAcount);
    }

    inputLoanAmount.value = '';
});

btnClose.addEventListener('click', function (e) {
    e.preventDefault();

    if (inputCloseUsername.value === currentAcount.username && +inputClosePin.value === currentAcount.pin) {
        const index = accounts.findIndex(acc => acc.username === currentAcount.username);

        accounts.splice(index, 1);

        containerApp.style.opacity = 0;
    };

    inputCloseUsername.value = inputClosePin.value = '';
});

btnSort.addEventListener('click', function(e) {
    e.preventDefault();

    displayMovements(currentAcount.movements, true)
});